<template>
    <section class="clientMessage-box">
        <a-form layout="horizontal" :form="form" @submit="submitMassage">
            <a-form-item :wrapperCol="{ span: 24 }" hasFeedback>
                <a-input type="text" placeholder="请输入姓名"
                         v-decorator="['name', {rules: [
                            { required: true, message: '请输入您的姓名', trigger: 'blur' }
                         ]}]">
                    <i slot="prefix" class="iconfont icon-gerenjibenxinxi" style="color:rgba(0,0,0,.25)"></i>
                </a-input>
            </a-form-item>
            <a-form-item :wrapperCol="{ span: 24 }" hasFeedback>
                <a-input type="number" placeholder="请输入手机号码"
                         v-decorator="['phone', {rules: [
                            {required: true, validator: this.phone_validation, trigger: 'blur' },
                        ]}]">
                    <i slot="prefix" class="iconfont icon-dianhua" style="color: rgba(0,0,0,.25)"></i>
                </a-input>
            </a-form-item>
            <a-form-item :wrapperCol="{ span: 24 }" hasFeedback>
                <a-input type="email" placeholder="请输入邮箱"
                         v-decorator="['email', {rules: [
                            {required: true, validator: this.email_validation, trigger: 'blur' },
                        ]}]">
                    <i slot="prefix" class="iconfont icon-dkw_youxiang" style="color: rgba(0,0,0,.25)"></i>
                </a-input>
            </a-form-item>
            <a-form-item :wrapperCol="{ span: 24 }" hasFeedback>
                <a-textarea placeholder="感兴趣的房源或城市（限制50位字符）" :autosize="{ maxRows: 2 }"
                            v-decorator="['interested', {rules: [
                                { required: true, message: '请输入感兴趣的海外房源或城市', trigger: 'blur' },
                            ]}]"/>
            </a-form-item>
            <a-form-item :wrapperCol="{ span: 24 }" hasFeedback>
                <a-select showSearch allowClear :getPopupContainer="getPopupContainer" placeholder="请选择所在城市" style="width: 100%"
                          v-decorator="['LocationCity', {rules: [
                                { required: true, message: '请选择您的所在城市', trigger: 'change' }
                          ]}]">
                    <a-select-option v-for="(item, index) in LocationListItem" :value="item.title" :key="item.title">{{ item.title }}</a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item :wrapperCol="{ span: 24 }" hasFeedback>
                <a-input-search type="number" @search="sendCode" placeholder="请输入验证码"
                                v-decorator="['code', {rules: [
                                    { required: true, validator: this.code_validation, trigger: 'blur' },
                                ]}]">
                    <i slot="prefix" class="iconfont icon-icon_sms" style="color:rgba(0,0,0,.25)"></i>
                    <a-button type="primary" slot="enterButton" :disabled="codeDisabled">{{ codeText }}</a-button>
                </a-input-search>
            </a-form-item>

            <a-form-item :wrapperCol="{ span: 24 }" style="text-align: center">
                <p>
                    <a-checkbox v-model="iAgreeChecked" @change="iAgreeonChange">我同意</a-checkbox>
                    <router-link to="/PrivacyAgreement" title="用户协议" alt="用户协议"></router-link>
                </p>
                <a-button htmlType="submit" type="primary" size="large" :disabled="submitMassageDisabled" style="padding: 6px 30px">
                    <i class="iconfont icon-submit"></i> 提交
                </a-button>
            </a-form-item>
        </a-form>

        <p v-show="false">{{getLocationList}}</p>
    </section>
</template>

<script>
    let phoneReg = /^(1)[3|4|5|6|7|8|9](\d){9}$/;

    export default {
        props: {
            //留言类型，type：1.购房意向、2.移民、3.留学、4.保险、5.1秒变身海外业主
            messageType: {
                type: Number,
                default: 1
            },
            //用户的手机号-美国保险页的banner图用户主动触发传递过来
            phone: {
                type: String,
                default: ''
            },

        },
        data() {
            return {
                form: this.$form.createForm(this),
                LocationListItem: [],   //用户所在城市列表
                verificationCode: '',   //验证码的验证串
                codeTime: 0,    //获取验证码倒计时
                codeText: '获取验证码',  //获取验证码按钮的提示文本
                codeDisabled: false,    //获取验证码按钮的状态
                iAgreeChecked: true,    //用户是否同意了用户协议
                submitMassageDisabled: false,   //提交按钮的状态

            }
        },
        computed: {
            //从state获取用户所在城市列表
            getLocationList() {
                if(this.$store.getters.get_LocationList){
                    //判断对象是否为空
                    if(Object.keys(this.$store.getters.get_LocationList).length != 0){
                        this.LocationListItem = this.$store.getters.get_LocationList;
                    }
                }
                return this.$store.getters.get_LocationList
            },
        },
        created() {
        },
        mounted() {
            // 防刷新：检测是否存在倒计时计算localStorage.codeTime
            this.isCodeTime();
        },
        methods: {
            // select组件——菜单渲染父节点。默认渲染到 body 上，如果你遇到菜单滚动定位问题，试试修改为滚动的区域，并相对其定位。
            getPopupContainer (trigger) {
                return trigger.parentElement
            },
            // 防刷新：检测是否存在倒计时计算localStorage.codeTime
            isCodeTime() {
                if (localStorage.codeTime) {
                    this.codeTime = parseInt(localStorage.codeTime);
                    this.codeText = this.codeTime + 's后重新获取';
                    this.codeDisabled = true;
                    let resend = setInterval(function () {
                        this.codeTime--;
                        if (this.codeTime > 0) {
                            this.codeText = this.codeTime + 's后重新获取';
                            localStorage.codeTime = this.codeTime;
                        } else {
                            localStorage.removeItem('codeTime');
                            clearInterval(resend);
                            this.codeText = '获取验证码';
                            this.codeDisabled = false;
                        }
                    }, 1000)
                }
            },
            //验证码倒计时计算
            codeCountdown() {
                if (this.codeTime > 0) {
                    this.codeTime--;
                    this.codeText = this.codeTime + 's后重新获取';
                    setTimeout(this.codeCountdown, 1000);
                    localStorage.codeTime = this.codeTime;
                } else {
                    this.codeTime = 0;
                    this.codeText = '获取验证码';
                    this.codeDisabled = false;
                    localStorage.removeItem('codeTime')
                }
            },
            //发送验证码
            sendCode() {
                let phone = this.form.getFieldValue('phone');
                // 手机号正则验证
                if (phoneReg.test(phone)) {
                    // 手机号符合验证
                    this.$get('/sms/message/' + phone).then(res => {
                        if (res.status == 0) {
                            this.codeTime = 60;
                            this.codeDisabled = true;
                            this.codeCountdown();
                            this.verificationCode = res.data;
                            this.$message.success( '发送成功，请您耐心等待短信通知。' )
                        } else {
                            this.$message.warning(res.msg);
                        }
                    })
                } else {
                    this.$message.error('手机号格式错误。')
                }
            },
            //用户是否同意了用户协议Change事件
            iAgreeonChange(){
                if(this.iAgreeChecked){
                    this.submitMassageDisabled = false;
                }else{
                    this.submitMassageDisabled = true;
                }
            },
            //提交留言
            submitMassage(e){
                e.preventDefault();
                this.form.validateFields((err, values) => {
                    if (!err) {
                        this.$post('/message/send', {
                            type: this.messageType, //留言类型，type：1.购房意向、2.移民、3.留学、4.保险、5.1秒变身海外业主
                            name: values.name, //客户姓名
                            phone: values.phone, //客户电话
                            email: values.email, //客户邮箱
                            message: values.interested, //感兴趣的房源或城市
                            location: values.LocationCity, //用户选择的所在城市
                            msg: values.code, //验证码
                            msgId: this.verificationCode,//验证码的验证串
                        }).then(res => {
                            if (res.status == 0) {
                                let tipMsg = '';
                                switch (this.messageType) {
                                    case 1:
                                        tipMsg = '购房意向';
                                        break;
                                    case 2:
                                        tipMsg = '移民';
                                        break;
                                    case 3:
                                        tipMsg = '留学';
                                        break;
                                    case 4:
                                        tipMsg = '保险/基金';
                                        break;
                                    case 5:
                                        tipMsg = '1秒变身海外业主';
                                        break;
                                    default:
                                        tipMsg = '购房意向';
                                }

                                this.$notification['success']({
                                    message: '华美优胜提示您：',
                                    description: `您的${ tipMsg }需求提交成功，华美优胜顾问团队将及时与您取得联系并提供专业的服务！`,
                                });

                                //清空表单数据
                                this.form.setFieldsValue({
                                    name: '',   //客户姓名
                                    phone: '', //客户电话
                                    email: '', //客户邮箱
                                    interested: '', //感兴趣的房源或城市
                                    LocationCity: '', //用户选择的所在城市
                                    code: '',   //验证码
                                });
                            } else {
                                this.$message.warning(res.msg);
                            }
                        })
                    }else{
                        this.$message.error('表单项输入有误，请检查并重新输入！');
                    }
                });
            },

        },
        components: {},
        watch: {
            //用户的手机号-美国保险页的banner图用户主动触发传递过来
            phone(val) {
                if (val !== '') {
                    console.log(val)
                    //给antd表单项赋值
                    this.form.setFieldsValue({
                        phone: val,
                    });
                }
            },
        }

    }
</script>

<style lang="less" type="text/less">
    body {
        .clientMessage-box {
            >form{
                padding: 10px;
                text-align: left;
                >p{
                    margin: 20px 0;
                    >a{
                        color: #f85148;
                    }
                }
            }
        }
    }
</style>
